/*
** free.c for newin-malloc in /home/leroy_v/newin-malloc
**
** Made by vincent leroy
** Login  <leroy_v@epitech.eu>
**
** Started on  Wed Feb 06 17:03:41 2013 vincent leroy
** Last update Thu Feb 07 16:10:24 2013 vincent leroy
*/

#include <pthread.h>
#include "malloc.h"

extern pthread_mutex_t __mutex1;

void	__free(header_t *cur)
{
    while (cur->back && cur->back->size == -1)
        cur = cur->back;
    if (cur->back)
        cur->back->next = NULL;
    else if (cur == __getFirstAllocated())
        __setFirstAllocated(NULL);
    if (brk(cur) == -1)
        show_alloc_mem();
    __setSbrk0(cur);
    UNLOCK;
}

void		free(void* ptr)
{
    header_t	*tmp;
    header_t	*cur;
    header_t	*cur2;

    if (!ptr)
        return;
    LOCK;
    tmp = SUB(ptr, sizeof(header_t));
    tmp->size = -1;
    cur = tmp;
    while (cur)
    {
        if (cur->size == -1)
        {
            cur2 = cur->next;
            while (cur2 && cur2->size == -1)
                cur2 = cur2->next;
            if (!cur2)
                return __free(cur);
            cur = cur2;
        }
        cur = cur->next;
    }
    UNLOCK;
}

void			show_alloc_mem()
{
    header_t	*head;
    header_t	*end;

    end = (header_t*)__getSbrk0();
    put("break : 0x");
    my_putaddr(end);
    put("\n");
    head = __getFirstAllocated();
    while (head && head < end)
    {
        if (head->size >= 0)
        {
            put("0x");
            my_putaddr(head);
            put(" - 0x");
            my_putaddr(ADD(head, head->size));
            put(" : ");
            my_putnbr(head->size);
            put(" octets\n");
        }
        head = head->next;
    }
}
